<template>
  <el-dialog
    class="add-association"
    width="550px"
    title="新建社群"
    v-model="visible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleAction(false)"
  >
    <el-form ref="formRef" :model="formParams" :rules="rules" label-position="top">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="城市标签" prop="cityName">
            <el-select
              v-model="formParams.cityName"
              @change="handleChangeCity"
              fit-input-width
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in cityNameOptions"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="点位名称" prop="positionId">
            <zzToolip ref="toolipRef" :content="content">
              <el-cascader
                ref="cascaderRef"
                placeholder="请输入"
                :options="positionOptions"
                clearable
                filterable
                :props="{ value: 'id', label: 'name', children: 'children' }"
                v-model="formParams.positionId"
                @change="handleChange"
              />
            </zzToolip>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="16">
          <el-form-item label="社群名称" prop="groupChatId">
            <el-select
              style="width: 300px"
              v-model="formParams.groupChatId"
              filterable
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in chatOptions"
                :key="item.groupChatId"
                :label="item.groupChatName"
                :value="item.groupChatId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="客服人员" prop="operationUserName">
            <el-input v-model="formParams.operationUserName" disabled />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <el-button :loading="submit" type="primary" @click="handleAction(true)"> 提交 </el-button>
      <el-button @click="handleAction(false)">取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { addAssociation, getAllPositions, getGroupChat } from '@/api/association'
import { ElMessage } from 'element-plus'
import zzToolip from './zzToolip.vue'
import useGlobalStore from '@/store/modules/global'

const globalStore = useGlobalStore()
const cityNameOptions = computed(() => globalStore.myCityList)

defineExpose({ init })
const emit = defineEmits(['refresh'])
const props = defineProps({
  dialogType: {
    type: String,
    default: ''
  }
})
const formRef = ref()
const cascaderRef = ref()

const positionOptions = ref([])
const chatOptions = ref([])

const checkUserName = (rule, value, callback) => {
  if (!value && (!formParams.positionId || !formParams.positionId.length)) {
    return callback(new Error(''))
  }
  if (!value && formParams.positionId && formParams.positionId.length) {
    callback(new Error('请去点位列表添加客服人员'))
  } else {
    callback()
  }
}

const rules = {
  groupChatId: [{ required: true, message: '', trigger: 'change' }],
  cityName: [{ required: true, message: '请选择', trigger: 'change' }],
  positionId: [
    {
      type: 'array',
      required: true,
      message: '',
      trigger: 'change'
    }
  ],
  operationUserName: [{ required: true, validator: checkUserName, trigger: 'change' }]
}

const submit = ref(false)
const visible = ref(false)
const formParams = reactive({
  positionId: [],
  groupChatId: '',
  operationUserName: '',
  operationUserId: '',
  groupChatName: '',
  cityName: ''
})

const content = ref('')

function handleChange(val) {
  const node = cascaderRef.value.getCheckedNodes()
  const nodeData = node && node.length ? node[0] : {}
  content.value = nodeData.text || ''
  formParams.operationUserName = nodeData?.data?.userName || ''
  formParams.operationUserId = nodeData?.data?.userId || ''
  formRef.value.validateField('operationUserName')
}

async function handleChangeCity() {
  const res = await getAllPositions({ cityName: formParams.cityName })
  const data = res?.data || []
  formParams.positionId = []
  positionOptions.value = data.map((item) => {
    if (item.children && item.children.length > 0) {
      item.children = item.children.map((item1) => {
        if (item1.children && item1.children.length > 0) {
          item1.children = item1.children.map((item2) => {
            if (!item2.children || item2.children.length === 0) {
              item2.disabled = true
            }
            return item2
          })
        } else {
          item1.disabled = true
        }
        return item1
      })
    } else {
      item.disabled = true
    }
    return item
  })
  formParams.operationUserName = ''
  formParams.operationUserId = ''
  content.value = ''
}

function handleAction(confirm) {
  if (confirm) {
    formRef.value?.validate((valid) => {
      if (valid) {
        submit.value = true
        const obj = (formParams.groupChatName = chatOptions.value.find(
          (i) => i.groupChatId === formParams.groupChatId
        ))
        const params = {
          ...formParams,
          positionId:
            formParams.positionId && formParams.positionId.length
              ? formParams.positionId[formParams.positionId.length - 1]
              : '',
          groupChatName: obj ? obj.groupChatName : ''
        }
        addAssociation(params)
          .then(() => {
            visible.value = false
            submit.value = false
            emit('refresh')
            formRef.value.resetFields()
            content.value = ''
            ElMessage({
              message: '提交成功',
              type: 'success'
            })
          })
          .catch(() => {
            submit.value = false
          })
      } else {
        ElMessage({
          message: '提交失败，请校验数据',
          type: 'error'
        })
      }
    })
  } else {
    formRef.value.resetFields()
    visible.value = false
    submit.value = false
    content.value = ''
  }
}

// 初始化
async function init(cityName) {
  formParams.cityName = cityName
  const res = await getAllPositions({ cityName })
  const ret = await getGroupChat({ cityName })
  const data = res?.data || []
  positionOptions.value = data.map((item) => {
    if (item.children && item.children.length > 0) {
      item.children = item.children.map((item1) => {
        if (item1.children && item1.children.length > 0) {
          item1.children = item1.children.map((item2) => {
            if (!item2.children || item2.children.length === 0) {
              item2.disabled = true
            }
            return item2
          })
        } else {
          item1.disabled = true
        }
        return item1
      })
    } else {
      item.disabled = true
    }
    return item
  })
  chatOptions.value = ret?.data || []
  visible.value = true
}
</script>

<style lang="scss" scoped>
:deep(.el-input-group__append) {
  background-color: #fff;
  color: var(--el-color-primary);
}
// .add-device .el-input {
//   width: 210px;
// }
</style>
